package ui.activity.group_management;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import controller.company.CompanyFeedAsync;
import controller.company.DownloadFileAsync;
import controller.company.SelectCompanyAsync;
import controller.group_management.DownloadMultiFilesAsync;
import controller.group_management.EditGroupDetailsAsync;
import controller.group_management.GroupManagementAsync;
import controller.group_management.PhotoAndVDOTabInGroupFeedFragmentAsync;
import controller.group_management.SettingTabInGroupFeedFragmentAsync;
import ui.activity.login.Login;
import ui.fragment.group_management.CreateGroupFragment;
import ui.fragment.group_management.GroupFeedFragment;
import ui.fragment.group_management.PhotoAndVDOTabInGroupFeedFragment;
import ui.fragment.group_management.SettingTabInGroupFeedFragment;

/**
 * Created by Dong Le on 6/19/2015.
 */
public class GroupFeed extends FragmentActivity implements View.OnClickListener{
    //View session
    public static ImageButton mIbtnAddMemberInGroupFeed;
    private ImageButton mIbtnBackInGroupFeed;
    public static ImageButton mIbtnUploadInGroupFeed;
    public static LinearLayout mLLUploadInGroupFeed;
    public static LinearLayout mLLDownloadInGroupFeed;
    public static TextView mTvCancelInGroupFeed;
    public static TextView mTvDoneInGroupFeed;
    public static TextView mTvDownloadInGroupFeed;
    public static TextView mTvGroupNameInGroupFeed;
    public static TextView mTvGroupNameInLlDownloadInGroupFeed;
    //Data session
    public static ArrayList<String> mAlFilesCheckedToDownload = new ArrayList<>();
    //The others Session
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            setDataForGroupFeed(Enterprise.groupManagement.getGroupNameSelected());
            loadGroupFeedFragment();
            mHandler.removeCallbacks(this);
        }
    };

    private Handler mHandler = new Handler();


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_add_member_in_group_feed_activity:
                // add member to member tab
                break;
            case R.id.ibtn_back_in_group_feed_activity:
                finish();
                break;
            case R.id.ibtn_upload_in_group_feed_activity:
                //upload file to Photo and videos tab
                break;
            case R.id.tv_cancel_in_group_feed_activity:
                cancelDownloadFeature();
                break;
            case R.id.tv_done_in_group_feed_activity:
                //edit group detail
                if (!"".equals(
                        SettingTabInGroupFeedFragment.mEtGroupNameInSettingTabInGroupFeedFragment
                                .getText().toString()) &&
                        !"".equals(
                                SettingTabInGroupFeedFragment.mEtGroupDescriptionInSettingTabInGroupFeedFragment
                                        .getText().toString())) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        new EditGroupDetailsAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                Login.user.getUserInfo().getAccessToken(),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                                "edit",
                                String.valueOf(
                                        Enterprise.groupManagement.getGroupIdSelected()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyIdGroup()),
                                SettingTabInGroupFeedFragment.
                                        mEtGroupNameInSettingTabInGroupFeedFragment.getText().toString(),
                                SettingTabInGroupFeedFragment.
                                        mEtGroupDescriptionInSettingTabInGroupFeedFragment.getText().toString());
                    else
                        new EditGroupDetailsAsync(this).execute(
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                Login.user.getUserInfo().getAccessToken(),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                                "edit",
                                String.valueOf(
                                        Enterprise.groupManagement.getGroupIdSelected()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyIdGroup()),
                                SettingTabInGroupFeedFragment.
                                        mEtGroupNameInSettingTabInGroupFeedFragment.getText().toString(),
                                SettingTabInGroupFeedFragment.
                                        mEtGroupDescriptionInSettingTabInGroupFeedFragment.getText().toString());
                } else {
                    Toast.makeText(getApplicationContext(),
                            getString(R.string.toast_error_edit_group), Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_download_in_group_feed_activity:
                //add files checked to template array for check multi download and reset files downloaded
                for (int i = 0 ; i < Enterprise.groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().size(); i ++) {
                    mAlFilesCheckedToDownload.add(PhotoAndVDOTabInGroupFeedFragmentAsync.mAlPhotoAndVDOTabInGroupFeed.get(
                            Enterprise.groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().
                            get(i).getPositionOfPhotoAndVdoIsCheckedInGroupFeedItem()
                    ).getmAlShotOfPhotoAndVDOTabInGroupFeedItem().get(
                            Enterprise.groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().
                            get(i).getPositionOfGridViewOfPhotoAndVdoIsCheckedInGroupFeedItem()
                    ).getPreviewMedium());
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    new DownloadMultiFilesAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                           mAlFilesCheckedToDownload.get(0));
                else
                    new DownloadMultiFilesAsync(this).execute(
                            mAlFilesCheckedToDownload.get(0));
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_feed);
        initialViews();
        initialData();
        callGroupDetailApi();
        /**
         * post delay to get number of shots and number of users before load Group feed fragment
         * because go to group feed from all company feed or group management
         */
        mHandler.postDelayed(mRunnable, 1000);
    }

    private void initialData() {
        mIbtnAddMemberInGroupFeed.setOnClickListener(this);
        mIbtnBackInGroupFeed.setOnClickListener(this);
        mIbtnUploadInGroupFeed.setOnClickListener(this);
        mTvCancelInGroupFeed.setOnClickListener(this);
        mTvDoneInGroupFeed.setOnClickListener(this);
        mTvDownloadInGroupFeed.setOnClickListener(this);
    }

    private void initialViews() {
        mIbtnAddMemberInGroupFeed = (ImageButton) findViewById(R.id.ibtn_add_member_in_group_feed_activity);
        mIbtnBackInGroupFeed = (ImageButton) findViewById(R.id.ibtn_back_in_group_feed_activity);
        mIbtnUploadInGroupFeed = (ImageButton) findViewById(R.id.ibtn_upload_in_group_feed_activity);
        mLLDownloadInGroupFeed = (LinearLayout) findViewById(R.id.ll_download_in_group_feed_activity);
        mLLUploadInGroupFeed = (LinearLayout) findViewById(R.id.ll_upload_in_group_feed_activity);
        mTvCancelInGroupFeed = (TextView) findViewById(R.id.tv_cancel_in_group_feed_activity);
        mTvDoneInGroupFeed = (TextView) findViewById(R.id.tv_done_in_group_feed_activity);
        mTvDownloadInGroupFeed = (TextView) findViewById(R.id.tv_download_in_group_feed_activity);
        mTvGroupNameInGroupFeed = (TextView) findViewById(R.id.tv_group_name_in_group_feed_activity);
        mTvGroupNameInLlDownloadInGroupFeed = (TextView) findViewById(R.id.tv_group_name_in_ll_download_in_group_feed_activity);
    }

    private void loadGroupFeedFragment() {
        getSupportFragmentManager().beginTransaction().replace(
                R.id.fl_in_group_feed_activity, GroupFeedFragment.newInstance()
        ).commitAllowingStateLoss();
    }

    public static void setDataForGroupFeed (String groupName) {
        Log.i("","Enterprise.groupManagement.getGroupNameSelected() " +Enterprise.groupManagement.getGroupNameSelected());
        mTvGroupNameInGroupFeed.setText(groupName);
        mTvGroupNameInLlDownloadInGroupFeed.setText(groupName);
    }
    //set action for tab group feed
    public static void setActionForTabGroupFeed(int pos_current_item) {
        switch (pos_current_item) {
            case 0:
                //photo and video tab
                GroupFeed.mIbtnAddMemberInGroupFeed.setVisibility(View.GONE);
                GroupFeed.mIbtnUploadInGroupFeed.setVisibility(View.VISIBLE);
                GroupFeed.mTvDoneInGroupFeed.setVisibility(View.GONE);
                break;
            case 1:
                //member tab
                GroupFeed.mIbtnAddMemberInGroupFeed.setVisibility(View.VISIBLE);
                GroupFeed.mIbtnUploadInGroupFeed.setVisibility(View.GONE);
                GroupFeed.mTvDoneInGroupFeed.setVisibility(View.GONE);
                //cancel download feature
                cancelDownloadFeature();
                break;
            case 2:
                //setting tab
                GroupFeed.mIbtnAddMemberInGroupFeed.setVisibility(View.GONE);
                GroupFeed.mIbtnUploadInGroupFeed.setVisibility(View.GONE);
                GroupFeed.mTvDoneInGroupFeed.setVisibility(View.VISIBLE);
                //cancel download feature
                cancelDownloadFeature();
                break;

        }
    }

    //cal group detail API to get number of shots and number of users
    private void callGroupDetailApi() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new SettingTabInGroupFeedFragmentAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                    String.valueOf(Login.user.getUserInfo().getAccessToken()),
                    String.valueOf(
                            Enterprise.company.getCompaniesOfUserInfoSelected().getUserCompanyId()),
                    String.valueOf(
                            Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                    String.valueOf(
                            Enterprise.groupManagement.getGroupIdSelected()),
                    "get_group_setting");
        else
            new SettingTabInGroupFeedFragmentAsync(this).execute(
                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                    String.valueOf(Login.user.getUserInfo().getAccessToken()),
                    String.valueOf(
                            Enterprise.company.getCompaniesOfUserInfoSelected().getUserCompanyId()),
                    String.valueOf(
                            Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                    String.valueOf(
                            Enterprise.groupManagement.getGroupIdSelected()),
                    "get_group_setting");
    }

    public static void cancelDownloadFeature () {
        //hide ll download and show ll upload
        mLLDownloadInGroupFeed.setVisibility(View.GONE);
        mLLUploadInGroupFeed.setVisibility(View.VISIBLE);
        //update data and ui of grid view
        if (Enterprise.groupManagement.
                getmAlPhotoAndVDOIsCheckedInGroupFeed() != null &&
                Enterprise.groupManagement.
                        getmAlPhotoAndVDOIsCheckedInGroupFeed().size() > 0) {
            for (int i = 0 ; i < Enterprise.
                    groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().size(); i++ ) {
                PhotoAndVDOTabInGroupFeedFragmentAsync.mAlPhotoAndVDOTabInGroupFeed.get(
                        Enterprise.
                                groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().
                                get(i).getPositionOfPhotoAndVdoIsCheckedInGroupFeedItem()
                ).getmAlShotOfPhotoAndVDOTabInGroupFeedItem().get(
                        Enterprise.
                                groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().
                                get(i).getPositionOfGridViewOfPhotoAndVdoIsCheckedInGroupFeedItem()
                ).setIsChecked(false);
            }
        }
        PhotoAndVDOTabInGroupFeedFragment.photoAndVDOTabInGroupFeedFragmentAdapter.notifyDataSetChanged();
        //clear data download
        Enterprise.groupManagement.setmAlPhotoAndVDOIsCheckedInGroupFeed(null);
    }
}
